from ui.components.base.widget import TgBaseWidget
from ui.components.layouts.vbox_layout import TgVBoxLayout
from ui.components.layouts.hbox_layout import TgHBoxLayout
from ui.components.inputs.label import TgLabel
from ui.components.buttons.button import TgButton
from ui.components.composite.plot_widget import TgPlotWidget
from ui.components.inputs.date_edit import TgDateEdit
from datetime import datetime, timedelta
from PySide6.QtWidgets import QScrollArea
from loguru import logger


class MarginTradingView(TgBaseWidget):
    
    def __init__(self):
        super().__init__()
        self.layout = TgVBoxLayout(self)
        self._setup_ui()
        
    def _setup_ui(self):
        self._create_controls()
        self._create_charts()

    def _create_controls(self):
        controls_layout = TgHBoxLayout()
        controls_layout.addWidget(TgLabel("起始时间:"))
        self.start_date_input = TgDateEdit()
        controls_layout.addWidget(self.start_date_input)
        
        controls_layout.addWidget(TgLabel("结束时间:"))
        self.end_date_input = TgDateEdit()
        controls_layout.addWidget(self.end_date_input)
        
        self.query_button = TgButton("查询")
        controls_layout.addWidget(self.query_button)
        controls_layout.addStretch(1)
        
        self.layout.addLayout(controls_layout)

    def _create_charts(self):
        scroll_area = QScrollArea()
        scroll_widget = TgBaseWidget()
        charts_layout = TgVBoxLayout(scroll_widget)
        
        self.charts = {}
        chart_configs = [
            ("financing_ratio", "融资买入额占全市场成交额比例(%)"),
            ("financing_balance", "融资余额"),
            ("financing_buy", "融资买入额"),
            ("sec_value", "融券余量金额"),
            ("sec_sell", "融券卖出量")
        ]
        
        for chart_id, title in chart_configs:
            chart = TgPlotWidget(title=title, time_axis=True)
            chart.setFixedHeight(300)
            chart.setObjectName(chart_id)
            chart.set_mouse_interaction(enabled=True)
            self.charts[chart_id] = chart
            charts_layout.addWidget(chart)
        
        scroll_area.setWidget(scroll_widget)
        scroll_area.setWidgetResizable(True)
        self.layout.addWidget(scroll_area)

    def set_default_dates(self, start_date: str, end_date: str):
        start_dt = datetime.strptime(start_date, '%Y-%m-%d').date()
        end_dt = datetime.strptime(end_date, '%Y-%m-%d').date()
        
        self.end_date_input.set_python_date(end_dt)
        self.start_date_input.set_python_date(start_dt)

    def get_date_range(self):
        start_date = self.start_date_input.get_date_string("yyyyMMdd")
        end_date = self.end_date_input.get_date_string("yyyyMMdd")
        return start_date, end_date

    def set_query_loading(self, is_loading: bool):
        self.query_button.setEnabled(not is_loading)
        self.query_button.setText("查询中..." if is_loading else "查询")

    def update_chart_data(self, chart_data: dict):
        # 先清空所有图表
        for chart in self.charts.values():
            chart.clear()

        if not chart_data:
            return

        # 更新融资买入比例图表
        financing_ratio_data = chart_data.get('financing_ratio')
        if financing_ratio_data:
            chart = self.charts['financing_ratio']
            
            # 添加融资买入占比（左y轴）
            chart.add_line_chart(
                x=financing_ratio_data['dates'],
                y=financing_ratio_data['ratios'],
                name="融资买入占比",
                color='#9b59b6'
            )
            
            # 添加百分位数曲线到右y轴
            chart.add_line_chart_right_axis(
                x=financing_ratio_data['dates'],
                y=financing_ratio_data['percentiles'],
                name="融资买入占比百分位数（滚动250日）",
                color='#e74c3c80',
                axis_label="百分位数 (%)"
            )

        # 更新其他图表
        chart_keys = ['financing_balance', 'financing_buy', 'sec_value', 'sec_sell']
        for chart_key in chart_keys:
            chart_series_data = chart_data.get(chart_key, [])
            if chart_series_data and chart_key in self.charts:
                chart = self.charts[chart_key]
                for series in chart_series_data:
                    chart.add_line_chart(
                        x=series['dates'],
                        y=series['values'],
                        name=series['name'],
                        color=series['color']
                    )

        # 自动调整所有图表的视图范围
        for chart in self.charts.values():
            chart.auto_range()

    def clear_all_charts(self):
        for chart in self.charts.values():
            chart.clear()